package org.netwia.networks;

import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.netwia.utils.ValidationUtils;

/**
 * Simplest connection between nodes based on the queue.
 * Produced output is put in the queue and served as an input.
 * When method outputProduced is called with null, exception is thrown.
 * 
 * @author radek.hecl
 *
 * @param <T> type of the network parameter
 */
public class SimpleQueueConnection<T> implements OutputListener<T>, InputProvider<T> {

    /**
     * Builder object.
     * 
     * @param <T> type of the network parameter
     */
    public static class Builder<T> {

        /**
         * Builds the result object.
         * 
         * @return created object
         */
        public SimpleQueueConnection<T> build() {
            return new SimpleQueueConnection<T>(this);
        }
    }

    /**
     * Queue for elements.
     */
    private Queue<T> queue = new LinkedBlockingQueue<T>();

    /**
     * Creates new instance.
     * 
     * @param builder builder object
     */
    public SimpleQueueConnection(Builder<T> builder) {
        guardInvariants();
    }

    /**
     * Guards this object to be consistent. Throws exception if this is not the case.
     */
    private void guardInvariants() {
    }

    @Override
    public boolean isNextInputReady() {
        return !queue.isEmpty();
    }

    @Override
    public T getNextInput() {
        T res = queue.poll();
        if (res == null) {
            throw new NoSuchElementException("no element on the input");
        }
        return res;
    }

    @Override
    public void outputProduced(T output) {
        ValidationUtils.guardNotNull(output, "null output is not allowed");
        queue.add(output);
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

}
